<template>
  <div class="page-container">
     <!--面包屑导航-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>会员中心</el-breadcrumb-item>
        <el-breadcrumb-item>折扣卡管理</el-breadcrumb-item>
        <el-breadcrumb-item>折扣卡列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar" >
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-row class="times mr30">

            <el-form-item prop="discountThemeName" label="折扣卡名称：" >
              <el-input clearable v-model="filters.discountThemeName" placeholder="输入折扣卡名称" maxlength="80"></el-input>
            </el-form-item>

            <el-form-item prop="startEndTime" label="有效期时间：" class="times">
              <el-date-picker
                v-model="filters.startEndTime"
                type="datetimerange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                size="mini"
                value-format="timestamp"
                ></el-date-picker>
            </el-form-item>

          </el-row>
        </el-row>
        <!--操作按钮-->
        <el-row class="search-button">
          <el-form-item>
            <kt-button :label="$t('action.reset')" class="resetButton" @click="resetForm('filters')" icon="el-icon-refresh"/>
          </el-form-item>
          <el-form-item>
            <kt-button icon="el-icon-search" label="搜索" class="searchButton" @click="findPageClick" />
          </el-form-item>
          <el-form-item>
            <kt-button label="创建折扣卡" @click="createPage()"  class="searchButton" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div class="tab-container">
      <!-- tbs标签 -->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane v-for="item in tabMapOptions" :key="item.key" :label="item.label" :name="item.key">
        </el-tab-pane>
      </el-tabs>
        <el-table :data="tableData" :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
          :highlight-current-row="true"
          :max-height="1500"
          v-loading="loading"
          :size="'mini'">
          <el-table-column  align="center" label="ID" min-width="250">
            <template slot-scope="scope">
              <span>{{ scope.row.discountThemeCode||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" label="折扣卡名称" min-width="220">
            <template slot-scope="scope">
              <span>{{ scope.row.discountThemeName||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" label="折扣" min-width="90">
            <template slot-scope="scope">
              <span>{{ scope.row.discountValue||'-'}}折</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" label="已生卡（张）" min-width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.generateNum||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" label="已绑定（张）" min-width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.bindingNum||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" label="有效期" min-width="380">
            <template slot-scope="scope">
              <span v-if="scope.row.startTime">{{ scope.row.startTime}} - {{scope.row.endTime}}</span>
              <span v-else-if="!scope.row.startTime">-</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" label="状态" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 1">待生卡</span>
              <span v-else-if="scope.row.status == 2">已生卡</span>
              <span v-else-if="scope.row.status == 3">已结束</span>
              <span v-else-if="scope.row.status == 4">已过期</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" label="所属组织" min-width="190">
            <template slot-scope="scope">
              <span>{{ scope.row.deptName||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" label="创建时间" min-width="190">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作"  min-width="550">
            <template slot-scope="scope">
              <kt-button v-if="[1,2].includes(scope.row.status) && scope.row.editFlag" @click="generateCard(scope.row)" type="text"  label="生成卡" perms="sys:role:edit"></kt-button>
              <kt-button v-if="[1,2,3,4].includes(scope.row.status) && scope.row.editFlag" @click="handleDetail(scope.row)" type="text"  label="查看" perms="sys:role:edit"></kt-button>
              <kt-button v-if="!scope.row.editFlag" @click="handleDetail(scope.row)" type="text"  label="查看" perms="sys:role:edit"></kt-button>
              <kt-button v-if="[1].includes(scope.row.status) && scope.row.editFlag" @click="updateDiscountTheme(scope.row)" type="text"  label="编辑" perms="sys:role:edit"></kt-button>
              <kt-button v-if="[2,3].includes(scope.row.status)" @click="checkTheme(scope.row)" type="text"  label="查看折扣卡" perms="sys:role:edit"></kt-button>
              <kt-button v-if="[2,3].includes(scope.row.status)" @click="generateCardRecordShow(scope.row)" type="text"  label="生卡记录" perms="sys:role:edit"></kt-button>
              <kt-button v-if="[2,3].includes(scope.row.status) && scope.row.editFlag" @click="cardBindingRecordShow(scope.row)" type="text"  label="绑卡记录" perms="sys:role:edit"></kt-button>
              <kt-button v-if="[1,4].includes(scope.row.status) && scope.row.editFlag" @click="deleteDiscountTheme(scope.row)" type="text"  label="删除" perms="sys:role:edit"></kt-button>
            </template>
          </el-table-column>
        </el-table>

        <!--分页栏-->
        <div class="toolbar t_r" >
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="refreshPageRequest"
            :current-page="filters.start"
            :page-size="filters.limit"
            :total="totalSize"
            :page-sizes="[10, 20, 30, 40]"
            @size-change="handleSizeChange"
          ></el-pagination>
        </div>
    </div>

    <!-- 生卡记录 -->
    <el-dialog :title="'生卡记录'" :visible.sync="generateDialogVisible" :close-on-click-modal="false">
      <div>
        <div class="flex">
          <el-form :inline="true" :model="generateRecordForm" :size="size" ref="generateRecordForm" >
            <el-form-item  class="mb30">
              <span class="color333 font14">折扣卡名称：</span>
              <span class="color333 font14">{{generateRecordForm.discountThemeName}}</span>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <div class="tab-container">
            <el-alert :closable="false" title type="success" />
            <el-table
              :data="generateRecordList"
              :highlight-current-row="true"
              :max-height="1500"
              v-loading="generateRecordLoading"
              :size="size"
              align="center"
            >
              <el-table-column prop="id" label="ID" align="center"></el-table-column>
              <el-table-column align="center" prop="periodNum" label="生卡张数"></el-table-column>
              <el-table-column align="center" prop="createTime" label="生卡时间"></el-table-column>
            </el-table>
            <div v-if="generateRecordList.length > 0" class="t_r">
              <el-pagination
                @size-change="generateHandleSizeChange"
                @current-change="generateHandleCurrentChange"
                :current-page="generateRecordForm.start"
                :page-sizes="[10]"
                :page-size="generateRecordForm.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="generateRecordTotal"
              ></el-pagination>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer t_c">
        <el-button class="searchButton" :size="size" @click.native="generateDialogVisible = false">确定</el-button>
      </div>
    </el-dialog>


      <!-- 绑卡记录 -->
    <el-dialog :title="'绑卡记录'" :visible.sync="bindingDialogVisible" :close-on-click-modal="false">
      <div>
        <div class="flex">
          <el-form :inline="true" :model="bindingRecordForm" :size="size" ref="bindingRecordForm" class="oh w100 mb30">
            <el-form-item class="mr683">
              <span class="font14 color333 lh32 h32 turnInlineBlock">折扣卡名称：</span>
              <span class="font14 color333 lh32 h32 turnInlineBlock">{{bindingRecordForm.discountThemeName}}</span>
            </el-form-item>
            <el-form-item  class="spec">
               <kt-button label="刷新" @click="cardBindingRecord()"  class="searchButton" />
            </el-form-item>
          </el-form>
        </div>
        <div>
          <div class="tab-container">
            <el-alert :closable="false" title type="success" />
            <el-table
              :data="bindingRecordList"
              :highlight-current-row="true"
              :max-height="1500"
              v-loading="bindingRecordLoading"
              :size="size"
              align="center"
            >
              <el-table-column prop="id" label="ID" align="center"></el-table-column>
              <el-table-column align="center" prop="periodNum" label="绑卡数量">
                <template slot-scope="scope">
                  <span v-if="scope.row.status == 1">-</span>
                  <span v-else-if="scope.row.status == 2">{{scope.row.periodNum}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="status" label="状态">
                <template slot-scope="scope">
                  <span v-if="scope.row.status == 1">执行中</span>
                  <span v-else-if="scope.row.status == 2">已完成</span>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="createTime" label="绑卡时间"></el-table-column>
            </el-table>
            <div v-if="bindingRecordList.length > 0" class="t_r">
              <el-pagination
                @size-change="bindingHandleSizeChange"
                @current-change="bindingHandleCurrentChange"
                :current-page="bindingRecordForm.start"
                :page-sizes="[10]"
                :page-size="bindingRecordForm.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="bindingRecordTotal"
              ></el-pagination>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer t_c">
        <el-button class="searchButton" :size="size" @click.native="bindingDialogVisible = false">确定</el-button>
      </div>
    </el-dialog>

    <!-- 生成折扣卡弹窗 -->
    <el-dialog title="生成折扣卡"  :visible.sync="discountCardDialogVisible"  :close-on-click-modal="false">
      <el-form :model="discountCardForm" label-position="right"  ref="discountCardForm" :rules="discountCardFormRules" class="mb60">
        <el-form-item class="mb30">
          <span class="color333 font14 ">折扣卡名称：</span>
          <span class="color333 font14">{{discountCardForm.discountThemeName}}</span>
        </el-form-item>
        <el-form-item class="mb30">
          <span class="color333 font14 w84 turnInlineBlock  t_r">折扣：</span>
          <span class="color333 font14">{{discountCardForm.discountValue}} 折</span>
        </el-form-item>
        <el-form-item class="mb30">
          <span class="color333 font14 w84 turnInlineBlock  t_r">有效期：</span>
          <span class="color333 font14">{{discountCardForm.startTime}} 至 {{discountCardForm.endTime}}</span>
        </el-form-item>
        <el-form-item label="生卡数量：" prop="periodNum" class="labelSize14" label-width="84px">
          <el-input v-model="discountCardForm.periodNum" autocomplete="off" maxlength="5" clearable class="w220"></el-input> 张
          <p style="color: #ffbf5e; margin-top: 10px;font-size: smaller;">为保证运行效率，单次生卡数量最多限5位数</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelButton" @click.native="discountCardDialogVisible=false" size="mini">取消</el-button>
        <el-button class="searchButton" @click="determineGenerate()" size="mini">确定生成</el-button>
      </div>
    </el-dialog>
    

  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { darkmagenta } from "color-name";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import cardRequest from "@/discountCard/request/cardRequest";

export default {
  name: "Tab",
  components: {
    KtButton,
    Treeselect,
    TableColumnFilterDialog,
  },
  data() {
    var validatePeriodNum = (rule, value, callback) => {
      let reg =/^[1-9]\d*$/;
      if (value == ''|| value == null) {
        callback(new Error('请输入生卡数量'));
      } if (!reg.test(value)) {
        callback(new Error('请输入正整数'));
      } else {
        callback();
      }
    };
    return {
      generateDialogVisible:false,//生卡记录弹窗
      generateRecordList:[],
      generateRecordTotal:0,
      generateRecordForm: {
        discountThemeId: null,
        discountThemeName:'',
        start:1,
        limit:10,
      },
      bindingDialogVisible:false,//生卡记录弹窗
      bindingRecordList:[],
      bindingRecordTotal:0,
      bindingRecordForm: {
        discountThemeId: null,
        discountThemeName:'',
        start:1,
        limit:10,
      },
      discountCardDialogVisible:false,//生成卡弹窗
      discountCardForm:{
        discountThemeId: null,
        periodNum:'',
      },
      discountCardFormRules: {
        periodNum: [
            { validator: validatePeriodNum, trigger: 'blur' }
          ],
      },
      deptType: localStorage.getItem('deptType'),
      startEndTime: [],
      // 有效期结束时间校验
      timeCheck: {
        disabledDate: time => {
          if (this.startEndTime) {
            return (
              time.getTime() < Date.now() - 8.64e7 ||
              time.getTime() > new Date(this.startEndTime).getTime()
            );
          } else {
            return time.getTime() < Date.now() - 8.64e7;
          }
        }
      },
      tabMapOptions: [
        { label: "全部", key: '0' },
        { label: "待生卡", key: '1' },
        { label: "已生卡", key: '2' },
        { label: "已结束", key: '3' },
        { label: "已过期", key: '4' }
      ],
      pageResult: {},
      filterColumns: [],
      tableData: [],
      totalSize:0,
      loading:false,
      generateRecordLoading:false,
      bindingRecordLoading:false,
      activeName: "0",
      size: "small",
      filters: {
        startEndTime:'',
        discountThemeName:'',
        start:1,
        limit:10,
      },
      selectName: null,
      selectDepart: {},
      clearOnSelect: true,
      options: [],
    };
  },
  methods: {

    // 获取当前选中部门的名称
    selectDept(val) {
      this.selectDepart = val;
      this.selectName = val.id;
    },
    //查询条件渲染
    findDeptTree(){
      let that = this;
      this.utils.request.getAuthorDeptTree({}, res => {
        if (res.code == "0000") {
          that.options = res.data;
          //that.selectName = localStorage.getItem('deptId');
        }
      });
    },
    //格式化组织初查询条件
    normalizer(node) {
      if ([1].includes(node.deptType) ||node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    //所属组织 清楚选择后
    deselect(){
      if(this.selectName == undefined || this.selectName == null){
        this.selectName = null;
      }
    },

    //点击搜索，页码重置
    findPageClick(){
      this.filters.start = 1;
      this.findPage();
    },

    // 获取分页数据
    findPage: function(data) {
      //子组件传过来的分页参数 data.start 当前页 data.limit 当前页总条数
      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      if(this_.filters.startEndTime!="" &&this_.filters.startEndTime!=null && this_.filters.startEndTime.length>0){
        this_.filters.startTime = this.filters.startEndTime[0];
        this_.filters.endTime = this.filters.startEndTime[1];
      }else{
        this_.filters.startTime = null;
        this_.filters.endTime = null;
      }
      this_.filters.deptId = this.selectName==null? localStorage.getItem('deptId') : this.selectName;
      this_.loading = true
      cardRequest.queryDiscountThemeList(this_.filters, function (res) {
        this_.loading = false
        if(res.code == "0000"){
          this_.tableData = res.data.rows
          this_.totalSize = res.data.total
        }
      });
    },
    // 换页刷新-start
    refreshPageRequest: function(val) {
      this.filters.start = val;
      this.findPage();
    },
    // 换页刷新-limit
    handleSizeChange: function(val) {
      this.filters.limit = val;
      this.filters.start = 1;
      this.findPage();
    },
    //创建
    createPage() {
      this.$router.push("/pages/DiscountCard/DiscountCardCreate/0");
    },
    updateDiscountTheme: function(data) {
        //this.$router.push(`/pages/DiscountCard/DiscountCardCreate?id=${data.id}`);
      this.$router.push({path:"/pages/DiscountCard/DiscountCardCreate/" + data.id});
    },
    //查看折扣卡规则
    handleDetail: function(data) {
      //this.$router.push(`/pages/DiscountCard/DiscountCardDetail?id=${data.id}`);
      this.$router.push({path:"/pages/DiscountCard/DiscountCardDetail/" + data.id});
    },
    //查看折扣卡
    checkTheme(data){
      //this.$router.push(`/pages/DiscountCard/DiscountCardBinding?id=${data.id}`);
      this.$router.push({path:"/pages/DiscountCard/DiscountCardBinding/" + data.id});
    },
    //查看生卡记录show
    generateCardRecordShow(data){
      let that = this;
      let params = {
        discountThemeId:data.id,
        discountThemeName:data.discountThemeName,
        periodType:1,
      }
      that.generateRecordForm = Object.assign(that.generateRecordForm, params);
      that.generateCardRecord();
    },
    //查看生卡记录
    generateCardRecord(){
      let that = this;
      that.generateRecordLoading = true;
      cardRequest.queryDiscountCardPeriodList(that.generateRecordForm, function (res) {
        that.generateRecordLoading = false;
        if (res.code == "0000") {
          that.generateRecordList = res.data.rows;
          that.generateRecordTotal = res.data.total;
        }else{
          that.generateRecordList = [];
          that.generateRecordTotal = 0;
        }
        that.generateDialogVisible = true;
      });
    },
    //生卡记录条数刷新
    generateHandleSizeChange(val) {
      this.generateRecordForm.start = val;
      this.generateCardRecord();
    },
    //生卡记录换页刷新
    generateHandleCurrentChange(val) {
      this.generateRecordForm.start = val;
      this.generateCardRecord();
    },
    //查看生卡记录show
    cardBindingRecordShow(data){
      let that = this;
      let params = {
        discountThemeId:data.id,
        discountThemeName:data.discountThemeName,
        periodType:2,
      }
      that.bindingRecordForm = Object.assign(that.bindingRecordForm, params);
      that.cardBindingRecord();
    },
    
    //查看绑卡记录
    cardBindingRecord(data){
      let that = this;
      that.bindingRecordLoading = true;
      cardRequest.queryDiscountCardPeriodList(that.bindingRecordForm, function (res) {
        that.bindingRecordLoading = false;
        if (res.code == "0000") {
          that.bindingRecordList = res.data.rows;
          that.bindingRecordTotal = res.data.total;
        }else{
          that.bindingRecordList = [];
          that.bindingRecordTotal = 0;
        }
        that.bindingDialogVisible = true;
      });
    },
    //绑卡记录条数刷新
    bindingHandleSizeChange(val) {
      this.bindingRecordForm.start = val;
      this.cardBindingRecord();
    },
    //绑卡记录换页刷新
    bindingHandleCurrentChange(val) {
      this.bindingRecordForm.start = val;
      this.cardBindingRecord();
    },
    //生成卡弹窗
    generateCard(data){
      this.discountCardForm.discountThemeId = data.id,
      this.discountCardForm = Object.assign(this.discountCardForm, data);
      this.discountCardForm.periodNum = null;
      this.discountCardDialogVisible = true;
      this.$nextTick(() => {
        this.$refs["discountCardForm"].clearValidate();
      });
    },
    //确定生成折扣卡
    determineGenerate(){
      let that = this;
      this.$refs.discountCardForm.validate(valid => {
        if(valid){
          cardRequest.generateDiscountCard(that.discountCardForm, function (res) {
            if (res.code == "0000") {
              that.$message({ message: res.data, type: "success" });
              that.findPage();
            }
            that.discountCardDialogVisible = false;
          });
        }
      })
    },
    // 删除折扣卡
    deleteDiscountTheme: function(data) {
      this.$confirm('<p>您确定要删除该折扣卡规则？</p><p style="color:red">删除后不可恢复</p>', "提示", {
        type: "warning",
        dangerouslyUseHTMLString: true,
        closeOnClickModal: false,
      }).then(() => {
        if (data != null) {
          var params = {};
          params.id = data.id;
          var this_ = this;
          cardRequest.deleteDiscountTheme(params, function(res) {
            if (res.code == "0000") {
              this_.$message({ message: "删除成功！", type: "success" });
              this_.findPage(null);
            } else {
              this_.$message({ message: "操作失败, " + res.msg, type: "error" });
            }
          });
        }
      }).catch(() => {
      });
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    //重置
    resetForm(formName) {
      this.selectName = localStorage.getItem('deptId');
      this.filters.deptId = localStorage.getItem('deptId');
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.filters.startTime = null;
        this.startEndTime = [];
        this.filters.endTime =  null;
        this.findPage();
      }
    },
  },
  watch: {
    activeName(val) {
      if(val != '0'){
        this.filters.status = val;
      }else{
        this.filters.status = null;
      }
      this.findPage();
    },

  },
  created() {
    // init the default selected tab
    const tab = this.$route.query.tab
    if (tab) {
      this.activeName = tab
    }
  },
  mounted() {
    this.findDeptTree();
    this.findPage();
  }
};
</script>

<style scoped lang="scss">
  .reset {
    background-color: #fff;
    color: #409eff;
  }
  
  // .flex {
  //   line-height: 3;
  //   padding: 15px;
  // }
  /deep/ .cell{
    .el-button{
      padding: 0 5px !important;
    }
}
.w220{
  width: 220px;
  /deep/ .el-input__inner{
    width: 220px;
  }
}
.labelSize14{
  /deep/ .el-form-item__label{
    font-size: 14px;
  }
}
.w84{
  width: 84px;
}
.lh32{
  line-height: 32px;
}
.h32{
  height: 32px;
}
.spec{
  /deep/ .el-form-item__content{
    margin-right: 0 !important;
  }
}
.mr683{
  margin-right: 683px !important;
}

</style>
